package org.ehe.business.overdue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.ehe.business.bom.domain.BomMaster;
import org.ehe.business.bom.service.BomMasterService;
import org.ehe.business.engineer.domain.EngineerEntity;
import org.ehe.business.engineer.service.EngineerService;
import org.ehe.business.overdue.domain.OverdueRecord;
import org.ehe.business.overdue.domain.OverdueRecordHistory;
import org.ehe.business.overdue.domain.bo.OverdueRecordBo;
import org.ehe.business.overdue.domain.vo.OverdueRecordVo;
import org.ehe.business.overdue.mapper.OverdueRecordMapper;
import org.ehe.business.overdue.service.OverdueRecordService;
import org.ehe.business.project.domain.ProjectEntity;
import org.ehe.business.project.domain.ProjectSolution;
import org.ehe.business.project.service.ProjectService;
import org.ehe.business.project.service.ProjectSolutionService;
import org.ehe.business.timeout.contants.BizTypeConstant;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.erp.domain.purchase.vo.ErpPurchaseOrderVo;
import org.ehe.erp.domain.quality.ErpQualityTask;
import org.ehe.erp.domain.quality.vo.ErpQualityFeedbackVo;
import org.ehe.erp.service.purchase.IErpPurchaseOrderService;
import org.ehe.erp.service.quality.ErpQualityFeedbackService;
import org.ehe.erp.service.quality.ErpQualityTaskService;
import org.ehe.system.domain.vo.SysUserVo;
import org.ehe.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;

/**
 * @author :zhangnn
 * @className :OverdueRecordServiceImpl
 * @description: TODO
 * @date 2025-10-14 16:25:06
 */
@Service
@RequiredArgsConstructor
public class OverdueRecordServiceImpl extends ServiceImpl<OverdueRecordMapper, OverdueRecord> implements OverdueRecordService {
    private final OverdueRecordMapper baseMapper;
    private final ProjectService projectService;
    private final ProjectSolutionService solutionService;
    private final EngineerService engineerService;
    private final ErpQualityTaskService qualityTaskService;
    private final BomMasterService bomMasterService;
    private final ISysUserService userService;
    private final IErpPurchaseOrderService purchaseOrderService;
    private final ErpQualityFeedbackService qualityFeedbackService;

    /**
     * 获取分页
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<OverdueRecordVo> queryPageList(OverdueRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OverdueRecord> lqw = buildWrapper(bo);
        IPage<OverdueRecordVo> overdueRecordVoIPage = baseMapper.selectVoPage(pageQuery.build(), lqw);
        overdueRecordVoIPage.getRecords().forEach(t->{
            if(t.getBizType().equals(BizTypeConstant.PROJECT+"Overdue")){
                ProjectEntity pe = projectService.getById(t.getBizId());
                if(Objects.nonNull(pe)){
                    t.setBizName("项目："+t.getBizName());
                    EngineerEntity engineer = engineerService.getById(pe.getAssignedEngineer());
                    if(Objects.nonNull(engineer)) {
                        t.setUserName(engineer.getName());
                    }
                }
            } else if(t.getBizType().equals(BizTypeConstant.SOLUTION+"Overdue")){
                ProjectSolution ps = solutionService.getById(t.getBizId());
                if(Objects.nonNull(ps)){
                    t.setBizName("方案："+t.getBizName());
                    SysUserVo sysUserVo = userService.selectUserByUserName(ps.getCreateBy());
                    t.setUserName(sysUserVo.getNickName());
                }
            } else if(t.getBizType().equals(BizTypeConstant.QUALITY+"Overdue")){
                ErpQualityTask task = qualityTaskService.getById(t.getBizId());
                if(Objects.nonNull(task)){
                    BomMaster bom = bomMasterService.getById(task.getBomId());
                    String name = "";
                    t.setBizName("质检:NO.["+task.getTaskNo()+"]");
                    if(Objects.nonNull(bom)){
                        name = bom.getBomName();
                        if(StringUtils.isBlank(task.getAssignUserName())){
                            t.setBizName("质检:NO.["+task.getTaskNo()+"]，BOM:"+name+"，分配人员！");
                        } else {
                            t.setUserName(task.getAssignUserName());
                            t.setBizName("质检:NO.["+task.getTaskNo()+"]，BOM:"+name);
                        }
                    }
                }
            } else if(t.getBizType().equals(BizTypeConstant.PURCHASEORDER+"Overdue")){
                ErpPurchaseOrderVo erpPurchaseOrderVo = purchaseOrderService.queryById(t.getBizId());
                if(Objects.nonNull(erpPurchaseOrderVo)){
                    t.setBizName("采购："+t.getBizName()+"-"+erpPurchaseOrderVo.getNo());
                    SysUserVo sysUserVo = userService.selectUserById(erpPurchaseOrderVo.getUpdateBy());
                    if(Objects.nonNull(sysUserVo)){
                        t.setUserName(sysUserVo.getNickName());
                    }
                }
            }
            else if(t.getBizType().equals(BizTypeConstant.BOM+"Overdue")){
                BomMaster bomMaster =  bomMasterService.getById(t.getBizId());
                if(Objects.nonNull(bomMaster)){
                    t.setBizName("BOM："+bomMaster.getBomName()+"-"+bomMaster.getBomCode());
                    SysUserVo sysUserVo = userService.selectUserByUserName(bomMaster.getUpdateBy());
                    if(Objects.nonNull(sysUserVo)){
                        t.setUserName(sysUserVo.getNickName());
                    }
                }
            }
            else if(t.getBizType().equals(BizTypeConstant.FEEDBACK+"Overdue")){
                ErpQualityFeedbackVo erpQualityFeedbackVo = qualityFeedbackService.queryById(t.getBizId());
                if(Objects.nonNull(erpQualityFeedbackVo)){
                    t.setBizName("反馈："+erpQualityFeedbackVo.getFeedbackNo()+"-"+erpQualityFeedbackVo.getProductName());
                    t.setUserName(erpQualityFeedbackVo.getFeedbackPerson());
                }
            }
            //报警历史记录
            List<OverdueRecordHistory> overdueRecordHistories = baseMapper.queryOverdueHistory(t.getId());
            t.setHistories(overdueRecordHistories);
            t.setCount(overdueRecordHistories.size());
        });
        return TableDataInfo.build(overdueRecordVoIPage);
    }

    @Override
    public List<OverdueRecordVo> queryList(OverdueRecordBo bo) {
        LambdaQueryWrapper<OverdueRecord> lqw = buildWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public OverdueRecordVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public Boolean insertByBo(OverdueRecordBo bo) {
        OverdueRecord record = MapstructUtils.convert(bo, OverdueRecord.class);
        return baseMapper.insert(record) > 0;
    }

    @Override
    public Boolean updateByBo(OverdueRecordBo bo) {
        OverdueRecord record = MapstructUtils.convert(bo, OverdueRecord.class);
        return baseMapper.updateById(record) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, boolean isValid) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean updateHandleStatus(Long id, Integer status) {
        OverdueRecord record = new OverdueRecord();
        record.setId(id);
        record.setHandleStatus(status);
        return baseMapper.updateById(record) > 0;
    }

    private LambdaQueryWrapper<OverdueRecord> buildWrapper(OverdueRecordBo bo) {
        LambdaQueryWrapper<OverdueRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBizType()), OverdueRecord::getBizType, bo.getBizType());
        lqw.eq(bo.getBizId() != null, OverdueRecord::getBizId, bo.getBizId());
        lqw.eq(bo.getHandleStatus() != null, OverdueRecord::getHandleStatus, bo.getHandleStatus());
        lqw.like(StringUtils.isNotBlank(bo.getBizName()), OverdueRecord::getBizName, bo.getBizName());
        lqw.orderByDesc(OverdueRecord::getCreateTime);
        return lqw;
    }

    /**
     * 提醒历史记录
     * @param id
     * @return
     */
    @Override
    public List<OverdueRecordHistory> queryOverdueHistory(Long id) {
        return baseMapper.queryOverdueHistory(id);
    }
}
